const byte TRIGGER_PIN = 2; const byte ECHO_PIN = 3; const unsigned long MEASURE_TIMEOUT = 25000UL; // 25ms = ~8m at 340m/s const float SOUND_SPEED = 340.0 / 1000; // In mm/µs void setup() { Serial.begin(115200); pinMode(TRIGGER_PIN, OUTPUT); digitalWrite(TRIGGER_PIN, LOW); // TRIGGER pin have to be low when no activate pinMode(ECHO_PIN, INPUT); } void loop() { /* 1. Start a mesure by sending a 10µs HIGH Impulse on TRIGGER pin */ digitalWrite(TRIGGER_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIGGER_PIN, LOW); /* 2. Mesure the time between the Impulse sending & is echo (if echo we are) */ long measure = pulseIn(ECHO_PIN, HIGH, MEASURE_TIMEOUT); /* 3. Calcul the distance with the mesured time (divide by 2 time sound speed cause the return count) */ float distance_mm = measure / 2.0 * SOUND_SPEED; /* Print the result in mm , cm & meter */ Serial.print(F("Distance: ")); Serial.print(distance_mm); Serial.print(F("mm (")); Serial.print(distance_mm / 10.0, 2); Serial.print(F("cm, ")); Serial.print(distance_mm / 1000.0, 2); Serial.println(F("m)")); delay(500); }